<!DOCTYPE HTML>
<html lang="zh-CN">


<head>
    <meta charset="utf-8">
    <meta name="keywords" content="【译】从OOP到函数式, 码道诚公">
    <meta name="description" content="">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=no">
    <meta name="renderer" content="webkit|ie-stand|ie-comp">
    <meta name="mobile-web-app-capable" content="yes">
    <meta name="format-detection" content="telephone=no">
    <meta name="apple-mobile-web-app-capable" content="yes">
    <meta name="apple-mobile-web-app-status-bar-style" content="black-translucent">
    <meta name="baidu-site-verification" content="code-oqVlgh2wQV" />
    <meta name="google-site-verification" content="Z-8Fm46WY6NL_3kxilmoqToW4jnvyF7boTgciTLBXUs" />
    <!-- Global site tag (gtag.js) - Google Analytics -->


    <title>【译】从OOP到函数式 | 码道诚公</title>
    <link rel="icon" type="image/png" href="/favicon.png">

    <link rel="stylesheet" type="text/css" href="/libs/awesome/css/all.css">
    <link rel="stylesheet" type="text/css" href="/libs/materialize/materialize.min.css">
    <link rel="stylesheet" type="text/css" href="/libs/aos/aos.css">
    <link rel="stylesheet" type="text/css" href="/libs/animate/animate.min.css">
    <link rel="stylesheet" type="text/css" href="/libs/lightGallery/css/lightgallery.min.css">
    <link rel="stylesheet" type="text/css" href="/css/matery.css">
    <link rel="stylesheet" type="text/css" href="/css/my.css">

    <script src="/libs/jquery/jquery.min.js"></script>

<meta name="generator" content="Hexo 5.2.0">
<style>.github-emoji { position: relative; display: inline-block; width: 1.2em; min-height: 1.2em; overflow: hidden; vertical-align: top; color: transparent; }  .github-emoji > span { position: relative; z-index: 10; }  .github-emoji img, .github-emoji .fancybox { margin: 0 !important; padding: 0 !important; border: none !important; outline: none !important; text-decoration: none !important; user-select: none !important; cursor: auto !important; }  .github-emoji img { height: 1.2em !important; width: 1.2em !important; position: absolute !important; left: 50% !important; top: 50% !important; transform: translate(-50%, -50%) !important; user-select: none !important; cursor: auto !important; } .github-emoji-fallback { color: inherit; } .github-emoji-fallback img { opacity: 0 !important; }</style>
<link rel="alternate" href="/atom.xml" title="码道诚公" type="application/atom+xml">
<link rel="stylesheet" href="/css/prism-tomorrow.css" type="text/css"></head>




<body>
    <header class="navbar-fixed">
    <nav id="headNav" class="bg-color nav-transparent">
        <div id="navContainer" class="nav-wrapper container">
            <div class="brand-logo">
                <a href="/" class="waves-effect waves-light">
                    
                    <img src="/medias/logo.png" class="logo-img" alt="LOGO">
                    
                    <span class="logo-span">码道诚公</span>
                </a>
            </div>
            

<a href="#" data-target="mobile-nav" class="sidenav-trigger button-collapse"><i class="fas fa-bars"></i></a>
<ul class="right nav-menu">
  
  <li class="hide-on-med-and-down nav-item">
    
    <a href="/" class="waves-effect waves-light">
      
      <i class="fas fa-home" style="zoom: 0.6;"></i>
      
      <span>首页</span>
    </a>
    
  </li>
  
  <li class="hide-on-med-and-down nav-item">
    
    <a href="/tags" class="waves-effect waves-light">
      
      <i class="fas fa-tags" style="zoom: 0.6;"></i>
      
      <span>标签</span>
    </a>
    
  </li>
  
  <li class="hide-on-med-and-down nav-item">
    
    <a href="/categories" class="waves-effect waves-light">
      
      <i class="fas fa-bookmark" style="zoom: 0.6;"></i>
      
      <span>分类</span>
    </a>
    
  </li>
  
  <li class="hide-on-med-and-down nav-item">
    
    <a href="/archives" class="waves-effect waves-light">
      
      <i class="fas fa-archive" style="zoom: 0.6;"></i>
      
      <span>归档</span>
    </a>
    
  </li>
  
  <li class="hide-on-med-and-down nav-item">
    
    <a href="/about" class="waves-effect waves-light">
      
      <i class="fas fa-user-circle" style="zoom: 0.6;"></i>
      
      <span>关于</span>
    </a>
    
  </li>
  
  <li class="hide-on-med-and-down nav-item">
    
    <a href="/contact" class="waves-effect waves-light">
      
      <i class="fas fa-comments" style="zoom: 0.6;"></i>
      
      <span>留言板</span>
    </a>
    
  </li>
  
  <li class="hide-on-med-and-down nav-item">
    
    <a href="/friends" class="waves-effect waves-light">
      
      <i class="fas fa-address-book" style="zoom: 0.6;"></i>
      
      <span>友情链接</span>
    </a>
    
  </li>
  
  <li>
    <a href="#searchModal" class="modal-trigger waves-effect waves-light">
      <i id="searchIcon" class="fas fa-search" title="搜索" style="zoom: 0.85;"></i>
    </a>
  </li>
</ul>


<div id="mobile-nav" class="side-nav sidenav">

    <div class="mobile-head bg-color">
        
        <img src="/medias/logo.png" class="logo-img circle responsive-img">
        
        <div class="logo-name">码道诚公</div>
        <div class="logo-desc">
            
            Never really desperate, only the lost of the soul.
            
        </div>
    </div>

    

    <ul class="menu-list mobile-menu-list">
        
        <li class="m-nav-item">
	  
		<a href="/" class="waves-effect waves-light">
			
			    <i class="fa-fw fas fa-home"></i>
			
			首页
		</a>
          
        </li>
        
        <li class="m-nav-item">
	  
		<a href="/tags" class="waves-effect waves-light">
			
			    <i class="fa-fw fas fa-tags"></i>
			
			标签
		</a>
          
        </li>
        
        <li class="m-nav-item">
	  
		<a href="/categories" class="waves-effect waves-light">
			
			    <i class="fa-fw fas fa-bookmark"></i>
			
			分类
		</a>
          
        </li>
        
        <li class="m-nav-item">
	  
		<a href="/archives" class="waves-effect waves-light">
			
			    <i class="fa-fw fas fa-archive"></i>
			
			归档
		</a>
          
        </li>
        
        <li class="m-nav-item">
	  
		<a href="/about" class="waves-effect waves-light">
			
			    <i class="fa-fw fas fa-user-circle"></i>
			
			关于
		</a>
          
        </li>
        
        <li class="m-nav-item">
	  
		<a href="/contact" class="waves-effect waves-light">
			
			    <i class="fa-fw fas fa-comments"></i>
			
			留言板
		</a>
          
        </li>
        
        <li class="m-nav-item">
	  
		<a href="/friends" class="waves-effect waves-light">
			
			    <i class="fa-fw fas fa-address-book"></i>
			
			友情链接
		</a>
          
        </li>
        
        
    </ul>
</div>


        </div>

        
    </nav>

</header>

    



<div class="bg-cover pd-header post-cover" style="background-image: url('/medias/featureimages/14.jpg')">
    <div class="container" style="right: 0px;left: 0px;">
        <div class="row">
            <div class="col s12 m12 l12">
                <div class="brand">
                    <h1 class="description center-align post-title">【译】从OOP到函数式</h1>
                </div>
            </div>
        </div>
    </div>
</div>




<main class="post-container content">

    
    <link rel="stylesheet" href="/libs/tocbot/tocbot.css">
<style>
    #articleContent h1::before,
    #articleContent h2::before,
    #articleContent h3::before,
    #articleContent h4::before,
    #articleContent h5::before,
    #articleContent h6::before {
        display: block;
        content: " ";
        height: 100px;
        margin-top: -100px;
        visibility: hidden;
    }

    #articleContent :focus {
        outline: none;
    }

    .toc-fixed {
        position: fixed;
        top: 64px;
    }

    .toc-widget {
        width: 345px;
        padding-left: 20px;
    }

    .toc-widget .toc-title {
        margin: 35px 0 15px 0;
        padding-left: 17px;
        font-size: 1.5rem;
        font-weight: bold;
        line-height: 1.5rem;
    }

    .toc-widget ol {
        padding: 0;
        list-style: none;
    }

    #toc-content {
        height: calc(100vh - 250px);
        overflow: auto;
    }

    #toc-content ol {
        padding-left: 10px;
    }

    #toc-content ol li {
        padding-left: 10px;
    }

    #toc-content .toc-link:hover {
        color: #42b983;
        font-weight: 700;
        text-decoration: underline;
    }

    #toc-content .toc-link::before {
        background-color: transparent;
        max-height: 25px;

        position: absolute;
        right: 23.5vw;
        display: block;
    }

    #toc-content .is-active-link {
        color: #42b983;
    }

    #floating-toc-btn {
        position: fixed;
        right: 15px;
        bottom: 76px;
        padding-top: 15px;
        margin-bottom: 0;
        z-index: 998;
    }

    #floating-toc-btn .btn-floating {
        width: 48px;
        height: 48px;
    }

    #floating-toc-btn .btn-floating i {
        line-height: 48px;
        font-size: 1.4rem;
    }
</style>
<div class="row">
    <div id="main-content" class="col s12 m12 l9">
        <!-- 文章内容详情 -->
<div id="artDetail">
    <div class="card">
        <div class="card-content article-info">
            <div class="row tag-cate">
                <div class="col s7">
                    
                    <div class="article-tag">
                        
                            <a href="/tags/%E5%87%BD%E6%95%B0%E5%BC%8F/">
                                <span class="chip bg-color">函数式</span>
                            </a>
                        
                            <a href="/tags/%E8%AF%91%E6%96%87/">
                                <span class="chip bg-color">译文</span>
                            </a>
                        
                            <a href="/tags/Scala/">
                                <span class="chip bg-color">Scala</span>
                            </a>
                        
                            <a href="/tags/Haskell/">
                                <span class="chip bg-color">Haskell</span>
                            </a>
                        
                    </div>
                    
                </div>
                <div class="col s5 right-align">
                    
                    <div class="post-cate">
                        <i class="fas fa-bookmark fa-fw icon-category"></i>
                        
                            <a href="/categories/%E5%87%BD%E6%95%B0%E5%BC%8F/" class="post-category">
                                函数式
                            </a>
                        
                    </div>
                    
                </div>
            </div>

            <div class="post-info">
                
                <div class="post-date info-break-policy">
                    <i class="far fa-calendar-minus fa-fw"></i>发布日期:&nbsp;&nbsp;
                    2021-08-24
                </div>
                

                

                
                <div class="info-break-policy">
                    <i class="far fa-file-word fa-fw"></i>文章字数:&nbsp;&nbsp;
                    5k
                </div>
                

                
                <div class="info-break-policy">
                    <i class="far fa-clock fa-fw"></i>阅读时长:&nbsp;&nbsp;
                    20 分
                </div>
                

                
            </div>
        </div>
        <hr class="clearfix">
        <div class="card-content article-card-content">
            <div id="articleContent">
                <p>从OOP切换到FP风格确实需要改变思维方式。在FP中，你不再有那些常用的原语，比如类、可变变量、循环等等。在最初的几个月里，你的效率不会很高，你会因为一些简单的事情卡上几个小时或几天，而这些事情以前通常只需要几分钟。这会很困难，你会觉得自己很愚蠢。我们都是这么过来的。但是度过这段时间后，你将获得超能力。我没听说过有谁是在每天做FP之后，又从FP转回OOP的。你可能会切换到一种不支持FP的语言，但你仍然会使用FP概念来编写代码，就是这么好。</p>
<p>在本文中，我将尝试分解一下概念，并回答在学习FP时困扰我的常见问题。</p>
<h2 id="1、这里没有类"><a href="#1、这里没有类" class="headerlink" title="1、这里没有类"></a>1、这里没有类</h2><blockquote>
<p>Q：没有类？那我怎么组织代码呢？</p>
</blockquote>
<p>事实证明，你不需要类。就像在旧的良好的面向过程编程中，你的程序只是一个函数的集合，区别在于，在FP中这些函数必须包含一些属性（稍后讨论），它们也必须互相<em>组合</em>。你会经常听到 “组合 “这个词，因为这是FP的核心思想之一。</p>
<p>我建议你不要再考虑“创建类的实例”或“调用类的方法”。你的程序将只是一堆可以互相调用的函数。</p>
<p><img src="/posts/4a84ab11/1*zo_Odo_8FnnCUjcSXCybqA.jpeg"></p>
<p>题外话：很多FP语言都有一个“类型类”的概念，不要与OOP中对类的理解相混淆。类型类的目的是为了提供多态性。一开始你还不必担心该问题，但是如果你感兴趣，请参阅文章：<a target="_blank" rel="noopener" href="https://medium.com/p/a9767f64ed2c?source=your_stories_page">Type classes explained</a>。</p>
<blockquote>
<p>Q：数据呢？我通常汇总一个类里面保存一些数据和修改这些数据的函数。</p>
</blockquote>
<p>对此，我们有代数数据类型（Algebraic Data Types ，ADT），这只是对持有数据的记录的一个花哨名称。</p>
<pre class=" language-scala"><code class="language-scala"><span class="token keyword">case</span> <span class="token keyword">class</span> Person<span class="token punctuation">(</span>name<span class="token operator">:</span> <span class="token builtin">String</span><span class="token punctuation">,</span> age<span class="token operator">:</span> <span class="token builtin">Int</span><span class="token punctuation">)</span></code></pre>
<pre class=" language-haskell"><code class="language-haskell"><span class="token keyword">data</span> <span class="token constant">Person</span> <span class="token operator">=</span> <span class="token constant">Person</span> <span class="token constant">String</span> <span class="token constant">Int</span>

<span class="token comment" spellcheck="true">-- OR</span>

<span class="token keyword">data</span> <span class="token constant">Person</span> <span class="token operator">=</span> <span class="token constant">Person</span>
  <span class="token punctuation">{</span> <span class="token hvariable">name</span> <span class="token operator">::</span> <span class="token constant">String</span>
  <span class="token punctuation">,</span> <span class="token hvariable">age</span> <span class="token operator">::</span> <span class="token constant">Int</span>
  <span class="token punctuation">,</span> <span class="token hvariable">address</span> <span class="token operator">::</span> <span class="token constant">Address</span>
  <span class="token punctuation">}</span></code></pre>
<p>你可以把它看作是一个只有构造函数的类。用FP术语来说，它们是“类型”，而构造函数称为“类型构造函数”。下面是构造类型并从中获取值的方法：</p>
<pre class=" language-scala"><code class="language-scala"><span class="token keyword">case</span> <span class="token keyword">class</span> Person<span class="token punctuation">(</span>name<span class="token operator">:</span> <span class="token builtin">String</span><span class="token punctuation">,</span> age<span class="token operator">:</span> <span class="token builtin">Int</span><span class="token punctuation">)</span>

<span class="token comment" spellcheck="true">// Using type constructor</span>
<span class="token keyword">val</span> person <span class="token operator">=</span> Person<span class="token punctuation">(</span><span class="token string">"Bob"</span><span class="token punctuation">,</span> <span class="token number">42</span><span class="token punctuation">)</span>

<span class="token comment" spellcheck="true">// Accessing fields</span>
<span class="token keyword">val</span> personsAge <span class="token operator">=</span> person<span class="token punctuation">.</span>age</code></pre>
<pre class=" language-haskell"><code class="language-haskell"><span class="token keyword">data</span> <span class="token constant">Person</span> <span class="token operator">=</span> <span class="token constant">Person</span>
  <span class="token punctuation">{</span> <span class="token hvariable">name</span> <span class="token operator">::</span> <span class="token constant">String</span>
  <span class="token punctuation">,</span> <span class="token hvariable">age</span> <span class="token operator">::</span> <span class="token constant">Int</span>
  <span class="token punctuation">,</span> <span class="token hvariable">address</span> <span class="token operator">::</span> <span class="token constant">Address</span>
  <span class="token punctuation">}</span>

<span class="token comment" spellcheck="true">-- Using type constructor</span>
<span class="token hvariable">person</span> <span class="token operator">=</span> <span class="token constant">Person</span> <span class="token string">"Bob"</span> <span class="token number">42</span>

<span class="token comment" spellcheck="true">-- Or using records notation</span>
<span class="token hvariable">person</span> <span class="token operator">=</span> <span class="token constant">Person</span> <span class="token punctuation">{</span><span class="token hvariable">name</span> <span class="token operator">=</span> <span class="token string">"Bob"</span><span class="token punctuation">,</span> <span class="token hvariable">age</span> <span class="token operator">=</span> <span class="token number">42</span><span class="token punctuation">}</span>

<span class="token comment" spellcheck="true">-- Accessing fields</span>
<span class="token hvariable">personsName</span> <span class="token operator">=</span> <span class="token hvariable">name</span> <span class="token hvariable">person</span> <span class="token comment" spellcheck="true">-- "Bob"</span></code></pre>
<p>注意，在Haskell中，<code>name</code>和<code>age</code>实际上是接受<code>Person</code>类型的值并返回其字段的函数。</p>
<blockquote>
<p>Q：好吧，但我如何改变这个人的年龄呢，举例说明下？</p>
</blockquote>
<p>在原地修改数据（在命令式编程理念中）是一种突变，而在FP中你不能执行突变（后面会有更多介绍）。如果你想改变什么东西——你可以复制一份。</p>
<pre class=" language-scala"><code class="language-scala"><span class="token keyword">val</span> bob <span class="token operator">=</span> Person<span class="token punctuation">(</span><span class="token string">"Bob"</span><span class="token punctuation">,</span> <span class="token number">42</span><span class="token punctuation">)</span>

<span class="token comment" spellcheck="true">// .copy provided by the 'case class'</span>
<span class="token keyword">val</span> olderBob <span class="token operator">=</span> bob<span class="token punctuation">.</span>copy<span class="token punctuation">(</span>age <span class="token operator">=</span> <span class="token number">43</span><span class="token punctuation">)</span></code></pre>
<pre class=" language-haskell"><code class="language-haskell"><span class="token hvariable">bob</span> <span class="token operator">=</span> <span class="token constant">Person</span> <span class="token string">"Bob"</span> <span class="token number">42</span>

<span class="token hvariable">olderBob</span> <span class="token operator">=</span> <span class="token hvariable">bob</span> <span class="token punctuation">{</span> <span class="token hvariable">age</span> <span class="token operator">=</span> <span class="token number">43</span> <span class="token punctuation">}</span></code></pre>
<p>有2种类型的ADT值得了解：<strong>乘积</strong>型与<strong>和</strong>型。</p>
<ul>
<li><p>乘积类型：一个字段的集合，要构造一个类型，必须指定所有字段。</p>
<pre class=" language-scala"><code class="language-scala"><span class="token comment" spellcheck="true">// Person is a product type consisting of 3 fields</span>
<span class="token keyword">case</span> <span class="token keyword">class</span> Person<span class="token punctuation">(</span>name<span class="token operator">:</span> <span class="token builtin">String</span><span class="token punctuation">,</span> age<span class="token operator">:</span> <span class="token builtin">Int</span><span class="token punctuation">,</span> address<span class="token operator">:</span> Address<span class="token punctuation">)</span>

<span class="token comment" spellcheck="true">// Address on its own also is a product type</span>
<span class="token keyword">case</span> <span class="token keyword">class</span> Address<span class="token punctuation">(</span>country<span class="token operator">:</span> <span class="token builtin">String</span><span class="token punctuation">,</span> city<span class="token operator">:</span> <span class="token builtin">String</span><span class="token punctuation">,</span> street<span class="token operator">:</span> <span class="token builtin">String</span><span class="token punctuation">)</span>

<span class="token comment" spellcheck="true">// In order to create a Point you have to provide all 3 arguments</span>
<span class="token keyword">case</span> <span class="token keyword">class</span> Point<span class="token punctuation">(</span>x<span class="token operator">:</span> <span class="token builtin">Double</span><span class="token punctuation">,</span> y<span class="token operator">:</span> <span class="token builtin">Double</span><span class="token punctuation">,</span> z<span class="token operator">:</span> <span class="token builtin">Double</span><span class="token punctuation">)</span></code></pre>
<pre class=" language-haskell"><code class="language-haskell"><span class="token comment" spellcheck="true">-- Person is a product type consisting of 3 fields</span>
<span class="token keyword">data</span> <span class="token constant">Person</span> <span class="token operator">=</span> <span class="token constant">Person</span>
  <span class="token punctuation">{</span> <span class="token hvariable">name</span> <span class="token operator">::</span> <span class="token constant">String</span>
  <span class="token punctuation">,</span> <span class="token hvariable">age</span> <span class="token operator">::</span> <span class="token constant">Int</span>
  <span class="token punctuation">,</span> <span class="token hvariable">address</span> <span class="token operator">::</span> <span class="token constant">Address</span>
  <span class="token punctuation">}</span>

<span class="token comment" spellcheck="true">-- Address is a product type on its own</span>
<span class="token keyword">data</span> <span class="token constant">Address</span> <span class="token operator">=</span> <span class="token constant">Address</span>
  <span class="token punctuation">{</span> <span class="token hvariable">country</span> <span class="token operator">::</span> <span class="token constant">String</span>
  <span class="token punctuation">,</span> <span class="token hvariable">city</span> <span class="token operator">::</span> <span class="token constant">String</span>
  <span class="token punctuation">,</span> <span class="token hvariable">street</span> <span class="token operator">::</span> <span class="token constant">String</span>
  <span class="token punctuation">}</span>

<span class="token comment" spellcheck="true">-- In order to create Position you have to provide all 3 coordinates</span>
<span class="token keyword">data</span> <span class="token constant">Position</span> <span class="token operator">=</span> <span class="token constant">Position</span>
  <span class="token punctuation">{</span> <span class="token hvariable">x</span> <span class="token operator">::</span> <span class="token constant">Integer</span>
  <span class="token punctuation">,</span> <span class="token hvariable">y</span> <span class="token operator">::</span> <span class="token constant">Integer</span>
  <span class="token punctuation">,</span> <span class="token hvariable">z</span> <span class="token operator">::</span> <span class="token constant">Integer</span>
  <span class="token punctuation">}</span></code></pre>
</li>
<li><p>和类型：表示可选性。你的类型可以是某一数据<strong>或者</strong>其它数据。例如，<em>形状</em>可以是<em>圆形</em>或<em>方形</em>。</p>
<pre class=" language-scala"><code class="language-scala"><span class="token comment" spellcheck="true">// Scala doesn't have a nice syntax for sum types so</span>
<span class="token comment" spellcheck="true">// it looks like a familiar OOP inheritance tree.</span>
<span class="token keyword">sealed</span> <span class="token keyword">trait</span> Shape

<span class="token comment" spellcheck="true">// But don't get confused: the 'extends' here stands for 'is'</span>
<span class="token comment" spellcheck="true">// relationship, not in a sense of 'extends and overrides methods'.</span>
<span class="token comment" spellcheck="true">// It only says that when you create a Circle it will be of type 'Shape'</span>
<span class="token keyword">case</span> <span class="token keyword">class</span> Circle<span class="token punctuation">(</span>radius<span class="token operator">:</span> <span class="token builtin">Int</span><span class="token punctuation">)</span> <span class="token keyword">extends</span> Shape

<span class="token keyword">case</span> <span class="token keyword">class</span> Square<span class="token punctuation">(</span>side<span class="token operator">:</span> <span class="token builtin">Int</span><span class="token punctuation">)</span> <span class="token keyword">extends</span> Shape</code></pre>
<pre class=" language-haskell"><code class="language-haskell"><span class="token comment" spellcheck="true">-- The | can be read as 'or'</span>
<span class="token keyword">data</span> <span class="token constant">Shape</span> <span class="token operator">=</span> <span class="token constant">Circle</span> <span class="token constant">Int</span> <span class="token operator">|</span> <span class="token constant">Square</span> <span class="token constant">Int</span>

<span class="token comment" spellcheck="true">-- Alternatively </span>
<span class="token keyword">data</span> <span class="token constant">Shape</span>
  <span class="token operator">=</span> <span class="token constant">Circle</span> <span class="token punctuation">{</span> <span class="token hvariable">radius</span> <span class="token operator">::</span> <span class="token constant">Int</span> <span class="token punctuation">}</span>
  <span class="token operator">|</span> <span class="token constant">Square</span> <span class="token punctuation">{</span> <span class="token hvariable">side</span> <span class="token operator">::</span> <span class="token constant">Int</span> <span class="token punctuation">}</span></code></pre>
</li>
</ul>
<p>ADT也可以嵌套：<em>Shape</em>是一种和类型，但其中每个选项本身可以是和类型或积类型。任何类型的领域模型都可以表示为和类型与积类型的组合。</p>
<blockquote>
<p>Q：为什么和与积如此特殊？</p>
</blockquote>
<p>除了作为建模的基本构件，它们还获得大多数FP语言的原生支持。积类型可以被解构和静态检查，而和类型可以用于模式匹配：</p>
<pre class=" language-scala"><code class="language-scala"><span class="token keyword">sealed</span> <span class="token keyword">trait</span> Shape

<span class="token keyword">case</span> <span class="token keyword">class</span> Circle<span class="token punctuation">(</span>radius<span class="token operator">:</span> <span class="token builtin">Int</span><span class="token punctuation">)</span> <span class="token keyword">extends</span> Shape

<span class="token keyword">case</span> <span class="token keyword">class</span> Rectangle<span class="token punctuation">(</span>width<span class="token operator">:</span> <span class="token builtin">Int</span><span class="token punctuation">,</span> height<span class="token operator">:</span> <span class="token builtin">Int</span><span class="token punctuation">)</span> <span class="token keyword">extends</span> Shape

<span class="token comment" spellcheck="true">// 'match' keyword allows us to pattern match on a </span>
<span class="token comment" spellcheck="true">// specific option of the sum type</span>
<span class="token keyword">def</span> area<span class="token punctuation">(</span>shape<span class="token operator">:</span> Shape<span class="token punctuation">)</span><span class="token operator">:</span> <span class="token builtin">Double</span> <span class="token operator">=</span> shape <span class="token keyword">match</span> <span class="token punctuation">{</span>
  <span class="token keyword">case</span> Circle<span class="token punctuation">(</span>r<span class="token punctuation">)</span> <span class="token keyword">=></span> math<span class="token punctuation">.</span>Pi <span class="token operator">*</span> r <span class="token operator">*</span> r
  <span class="token keyword">case</span> Rectangle<span class="token punctuation">(</span>w<span class="token punctuation">,</span> h<span class="token punctuation">)</span> <span class="token keyword">=></span> w <span class="token operator">*</span> h <span class="token comment" spellcheck="true">// Note how rectangle's width and height </span>
                                <span class="token comment" spellcheck="true">// are captured in 'w' and 'h'. It's possible</span>
                                <span class="token comment" spellcheck="true">// because Rectange is a product type</span>
<span class="token punctuation">}</span></code></pre>
<pre class=" language-haskell"><code class="language-haskell"><span class="token keyword">data</span> <span class="token constant">Shape</span>
  <span class="token operator">=</span> <span class="token constant">Circle</span> <span class="token punctuation">{</span> <span class="token hvariable">radius</span> <span class="token operator">::</span> <span class="token constant">Double</span> <span class="token punctuation">}</span>
  <span class="token operator">|</span> <span class="token constant">Rectangle</span> <span class="token punctuation">{</span> <span class="token hvariable">width</span> <span class="token operator">::</span> <span class="token constant">Double</span>
              <span class="token punctuation">,</span> <span class="token hvariable">height</span> <span class="token operator">::</span> <span class="token constant">Double</span> <span class="token punctuation">}</span>

<span class="token comment" spellcheck="true">-- In haskell different options of a sum type can</span>
<span class="token comment" spellcheck="true">-- be handled with different 'functions'</span>
<span class="token hvariable">area</span> <span class="token operator">::</span> <span class="token constant">Shape</span> <span class="token operator">-></span> <span class="token constant">Double</span>
<span class="token hvariable">area</span> <span class="token punctuation">(</span><span class="token constant">Circle</span> <span class="token hvariable">r</span><span class="token punctuation">)</span> <span class="token operator">=</span> <span class="token builtin">pi</span> <span class="token operator">*</span> <span class="token hvariable">r</span> <span class="token operator">*</span> <span class="token hvariable">r</span>
<span class="token hvariable">area</span> <span class="token punctuation">(</span><span class="token constant">Rectangle</span> <span class="token hvariable">w</span> <span class="token hvariable">h</span><span class="token punctuation">)</span> <span class="token operator">=</span> <span class="token hvariable">w</span> <span class="token operator">*</span> <span class="token hvariable">h</span> <span class="token comment" spellcheck="true">-- width and height are captured in 'w' and 'h' </span>
                             <span class="token comment" spellcheck="true">-- because Rectangle is a product type</span></code></pre>
<h2 id="2、你需要的只有函数"><a href="#2、你需要的只有函数" class="headerlink" title="2、你需要的只有函数"></a>2、你需要的只有函数</h2><p>认识一下你的新朋友——函数。你可能知道它的不同名字：getter、setter、构造函数、方法、builder、静态函数等。在OOP中，这些名字与不同的背景相关，并具有不同的属性。在FP中，函数始终只是一个函数——它接受值作为输入，并返回值作为输出。</p>
<p>使用函数不需要实例化任何东西（因为没有类），你只需要导入定义函数的模块并直接调用它。一个函数式程序只是ADT和函数的集合，就像前面的<code>Shape</code>例子一样。</p>
<p>一个函数应该有3个主要属性：</p>
<ul>
<li><strong>Pure</strong>：纯粹性，没有副作用。函数不允许做超过其类型定义所规定的事情。例如，接受<code>Int</code>值并返回<code>Int</code>值的函数不能修改全局变量、访问文件系统、执行网络请求等。它<em>只能</em>对输入值做一些运算并返回某些值。</li>
<li><strong>Total</strong>：完全性，为所有输入都返回值。对于某些属性会崩溃或抛出异常的函数是非完全函数或部分函数。例如，<code>div</code>函数：类型声明承诺它会接收一个<code>Int</code>并返回一个<code>Int</code>。但是如果第二个参数是<code>0</code>，将会抛出“被零除”异常，因此它不是完全的。</li>
<li><strong>Deterministic</strong>：确定性，对于相同的输入会返回相同的结果。对于确定性函数，无论如何以及何时调用它，它总是返回相同的值。依赖于当前日期、时间、时区或一些外部状态的函数不是确定性的。</li>
</ul>
<p>大多数编程语言都不能静态地保证这些属性，所以满足这些属性是程序员的责任。举例来说，Scala编译器很乐意接受不纯粹的、部分的和非确定性的函数：</p>
<pre class=" language-scala"><code class="language-scala"><span class="token comment" spellcheck="true">// Just an example, don't do this at home</span>
<span class="token keyword">def</span> isPositive<span class="token punctuation">(</span>number<span class="token operator">:</span> <span class="token builtin">Int</span><span class="token punctuation">)</span><span class="token operator">:</span> <span class="token builtin">Boolean</span> <span class="token operator">=</span> <span class="token punctuation">{</span>
  <span class="token keyword">if</span> <span class="token punctuation">(</span>number <span class="token operator">==</span> <span class="token number">0</span><span class="token punctuation">)</span>
    <span class="token keyword">throw</span> <span class="token keyword">new</span> Exception<span class="token punctuation">(</span><span class="token string">"meh"</span><span class="token punctuation">)</span> <span class="token comment" spellcheck="true">// Partial (non total)</span>
  <span class="token keyword">else</span> <span class="token punctuation">{</span>
    println<span class="token punctuation">(</span><span class="token string">"Calling isPositive!"</span><span class="token punctuation">)</span> <span class="token comment" spellcheck="true">// Impure (writing to std out is a side effect)</span>

    <span class="token keyword">if</span> <span class="token punctuation">(</span>System<span class="token punctuation">.</span>currentTimeMillis<span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token operator">%</span> <span class="token number">2</span> <span class="token operator">==</span> <span class="token number">0</span><span class="token punctuation">)</span> <span class="token comment" spellcheck="true">// Non deterministic</span>
      number <span class="token operator">></span> <span class="token number">0</span>
    <span class="token keyword">else</span>
      number <span class="token operator">&lt;</span> <span class="token number">0</span>
  <span class="token punctuation">}</span>
<span class="token punctuation">}</span></code></pre>
<p>另一方面，在Haskell中，你不能（很容易地）写出一个不纯粹或非确定性的函数：任何类型的副作用函数都会返回一个IO，这个值表示“有副作用的”计算。完全性仍然由程序员掌控，因为你可以抛出异常或返回所谓的bottom，这将会终止程序。</p>
<pre class=" language-haskell"><code class="language-haskell"><span class="token hvariable">isPositive</span> <span class="token operator">::</span> <span class="token constant">Int</span> <span class="token operator">-></span> <span class="token constant">Bool</span>
<span class="token hvariable">isPositive</span> <span class="token hvariable">number</span> <span class="token operator">=</span> <span class="token builtin">undefined</span> <span class="token comment" spellcheck="true">-- compiles but throws exception when called </span>

<span class="token comment" spellcheck="true">-- Or</span>
<span class="token hvariable">isPositive</span> <span class="token hvariable">number</span> <span class="token operator">=</span> <span class="token builtin">error</span> <span class="token string">"meh"</span> <span class="token comment" spellcheck="true">-- same</span></code></pre>
<blockquote>
<p>Q：为什么我要关心一个函数是否满足这些性质？</p>
</blockquote>
<p>如果一个函数满足这些性质，它就具有了“引用透明性”（详见<a target="_blank" rel="noopener" href="https://medium.com/@olxc/referential-transparency-93352c2dd713">另一篇文章</a>）。简而言之，你就可以通过查看函数类型定义，准确地知道它能做什么和不能做什么。你可以无所畏惧的重构代码，因为引用透明性保证你不会出现任何问题。引用透明性让我们可以控制软件的复杂性。OOP中的重构可能是一场噩梦，因为直到真正运行程序并在头脑中构建一个模型后时，你才知道哪些对象在什么时候调用了什么方法。即便如此，这也不是一件容易的事。</p>
<h2 id="3、你不能修改变量"><a href="#3、你不能修改变量" class="headerlink" title="3、你不能修改变量"></a>3、你不能修改变量</h2><blockquote>
<p>Q：这是最奇怪的部分，我如何在不修改变量的情况下做出有用的东西？</p>
</blockquote>
<p>如果你有一个变量<code>person</code>与 <code>Person("Bob", 42)</code> 绑定，你就不能将它重新绑定到<code>Person("Bob",43)</code>。你<em>可以</em>做的就是通过创建一个副本并指定你要改变的内容来创建一个不同的变量（就像我们之前讨论的那样）。变量是不可改变的，只用作别名或<strong>标记值</strong>，而不是一个物理引用或指向真实数据的指针。</p>
<blockquote>
<p>Q：为什么不干脆在原地修改变量？</p>
</blockquote>
<p>因为它破坏了引用透明性，正如我之前所说，引用透明性是FP的关键。它可以使你的生活更加轻松，而没有可变变量就是一个公平的代价。此外，没有可变变量意味着你可以免费获得线程安全的代码，不会再因为“只在周二晚上发生”的并发错误而浪费周末的时间。</p>
<p>不可变性是一个简单的概念，但是在多年的OOP开发经验之后，它就很难被接受了。我们经常看到人们在Scala中使用<code>var</code>，就是为了“让这个对象能工作”。一开始这样做是可以的，但一定要寻找一个不可变的实现。此外，在Haskell中没有这样的“技巧”，所以你必须从一开始就做到不可变。</p>
<h2 id="4、你不能执行“for”循环"><a href="#4、你不能执行“for”循环" class="headerlink" title="4、你不能执行“for”循环"></a>4、你不能执行“for”循环</h2><blockquote>
<p>Q：我们的面包与黄油——“for”循环——你说FP中也没有？那如何对数组进行迭代？</p>
</blockquote>
<p>没有突变就意味着没有<code>for</code>循环，因为它通常需要在满足条件之前修改一些计数器“i”。然而，我们有其它方法（递归和高阶函数）来实现同样的目的。</p>
<h3 id="递归"><a href="#递归" class="headerlink" title="递归"></a>递归</h3><p>你必须适应递归，因为它在FP中无处不在。例如，一个列表中所有数字之和看起来可能是这样的：</p>
<pre class=" language-scala"><code class="language-scala"><span class="token comment" spellcheck="true">// 'List' is defined as a sum type so we can use pattern matching.</span>
<span class="token comment" spellcheck="true">// There are two type constructors we need to check: one for empty list and</span>
<span class="token comment" spellcheck="true">// one for head and tail:</span>
<span class="token keyword">def</span> sum<span class="token punctuation">(</span>lst<span class="token operator">:</span> List<span class="token punctuation">[</span><span class="token builtin">Int</span><span class="token punctuation">]</span><span class="token punctuation">)</span><span class="token operator">:</span> <span class="token builtin">Int</span> <span class="token operator">=</span> lst <span class="token keyword">match</span> <span class="token punctuation">{</span>
  <span class="token keyword">case</span> Nil <span class="token keyword">=></span> <span class="token number">0</span> <span class="token comment" spellcheck="true">// Nil is a type constructor for an empty list</span>
  <span class="token keyword">case</span> x <span class="token operator">:</span><span class="token operator">:</span> xs <span class="token keyword">=></span> x <span class="token operator">+</span> sum<span class="token punctuation">(</span>xs<span class="token punctuation">)</span> <span class="token comment" spellcheck="true">// x :: xs looks weird but it's actually just</span>
                              <span class="token comment" spellcheck="true">// a product type named '::' and can be rewritten as</span>
                              <span class="token comment" spellcheck="true">// case ::(x, xs) => ...</span>
                              <span class="token comment" spellcheck="true">// Scala allows infix operators for type constructors</span>
                              <span class="token comment" spellcheck="true">// so it's possible to say 'case x :: xs'</span>
<span class="token punctuation">}</span>

sum<span class="token punctuation">(</span>List<span class="token punctuation">(</span><span class="token number">1</span><span class="token punctuation">,</span><span class="token number">2</span><span class="token punctuation">,</span><span class="token number">3</span><span class="token punctuation">,</span><span class="token number">4</span><span class="token punctuation">,</span><span class="token number">5</span><span class="token punctuation">)</span><span class="token punctuation">)</span> <span class="token comment" spellcheck="true">// 15</span>

<span class="token comment" spellcheck="true">// This is just an example, as there is a built in sum function that</span>
<span class="token comment" spellcheck="true">// can be used as List(1,2,3,4,5).sum</span></code></pre>
<pre class=" language-haskell"><code class="language-haskell"><span class="token comment" spellcheck="true">-- Similar to Scala version, List is just a sum type with two options</span>
<span class="token comment" spellcheck="true">-- [] is a type constructor for an empty list</span>
<span class="token hvariable">mySum</span> <span class="token operator">::</span> <span class="token punctuation">[</span><span class="token constant">Int</span><span class="token punctuation">]</span> <span class="token operator">-></span> <span class="token constant">Int</span>
<span class="token hvariable">mySum</span> <span class="token punctuation">[</span><span class="token punctuation">]</span> <span class="token operator">=</span> <span class="token number">0</span>
<span class="token hvariable">mySum</span> <span class="token punctuation">(</span><span class="token hvariable">x</span> <span class="token operator">:</span> <span class="token hvariable">xs</span><span class="token punctuation">)</span> <span class="token operator">=</span> <span class="token hvariable">x</span> <span class="token operator">+</span> <span class="token punctuation">(</span><span class="token hvariable">mySum</span> <span class="token hvariable">xs</span><span class="token punctuation">)</span>

<span class="token comment" spellcheck="true">-- We will step through the list building a sum expression until we hit</span>
<span class="token comment" spellcheck="true">-- the empty list case which returns 0. That will close the loop and</span>
<span class="token comment" spellcheck="true">-- the built up expression will be summed up</span></code></pre>
<p>使用递归数据结构是很常见的，比如列表或树。甚至自然数也可以用这种方式表示。遍历这些数据结构的自然方法是对类型构造器进行模式匹配，并将递归函数应用到数据结构的递归部分。一般模式是首先定义一个基本分支，比如空列表分支来终止递归，然后再定义一个一般的分支。</p>
<h3 id="高阶函数"><a href="#高阶函数" class="headerlink" title="高阶函数"></a>高阶函数</h3><p>高阶函数将其它函数作为参数。说到迭代，你必须知道如何使用<code>map</code>和<code>fold</code>：</p>
<pre class=" language-scala"><code class="language-scala"><span class="token comment" spellcheck="true">// Pass a function to transform every item in the list</span>
List<span class="token punctuation">(</span><span class="token number">1</span><span class="token punctuation">,</span><span class="token number">2</span><span class="token punctuation">,</span><span class="token number">3</span><span class="token punctuation">,</span><span class="token number">4</span><span class="token punctuation">,</span><span class="token number">5</span><span class="token punctuation">)</span><span class="token punctuation">.</span>map<span class="token punctuation">(</span>n <span class="token keyword">=></span> n <span class="token operator">+</span> <span class="token number">1</span><span class="token punctuation">)</span> <span class="token comment" spellcheck="true">// List(2,3,4,5,6)</span>

<span class="token comment" spellcheck="true">// Or shorter syntax</span>
List<span class="token punctuation">(</span><span class="token number">1</span><span class="token punctuation">,</span><span class="token number">2</span><span class="token punctuation">,</span><span class="token number">3</span><span class="token punctuation">,</span><span class="token number">4</span><span class="token punctuation">,</span><span class="token number">5</span><span class="token punctuation">)</span><span class="token punctuation">.</span>map<span class="token punctuation">(</span>_ <span class="token operator">*</span> <span class="token number">2</span><span class="token punctuation">)</span> <span class="token comment" spellcheck="true">// List(2,4,6,8,10)</span>

<span class="token comment" spellcheck="true">// Fold example. Sum all the values in a list</span>
List<span class="token punctuation">(</span><span class="token number">1</span><span class="token punctuation">,</span><span class="token number">2</span><span class="token punctuation">,</span><span class="token number">3</span><span class="token punctuation">,</span><span class="token number">4</span><span class="token punctuation">,</span><span class="token number">5</span><span class="token punctuation">)</span><span class="token punctuation">.</span>fold<span class="token punctuation">(</span><span class="token number">0</span><span class="token punctuation">)</span><span class="token punctuation">(</span><span class="token punctuation">(</span>l<span class="token punctuation">,</span> r<span class="token punctuation">)</span> <span class="token keyword">=></span> l <span class="token operator">+</span> r<span class="token punctuation">)</span> <span class="token comment" spellcheck="true">// 15</span>

<span class="token comment" spellcheck="true">// Multiply each number by 2, convert to string and </span>
<span class="token comment" spellcheck="true">// produce a total string appending the results together</span>
List<span class="token punctuation">(</span><span class="token number">1</span><span class="token punctuation">,</span><span class="token number">2</span><span class="token punctuation">,</span><span class="token number">3</span><span class="token punctuation">,</span><span class="token number">4</span><span class="token punctuation">,</span><span class="token number">5</span><span class="token punctuation">)</span><span class="token punctuation">.</span>foldLeft<span class="token punctuation">(</span><span class="token string">""</span><span class="token punctuation">)</span><span class="token punctuation">(</span><span class="token punctuation">(</span>acc<span class="token punctuation">,</span> number<span class="token punctuation">)</span> <span class="token keyword">=></span> acc <span class="token operator">++</span> <span class="token punctuation">(</span>number <span class="token operator">*</span> <span class="token number">2</span><span class="token punctuation">)</span><span class="token punctuation">.</span>toString<span class="token punctuation">)</span> <span class="token comment" spellcheck="true">// "246810"</span></code></pre>
<pre class=" language-haskell"><code class="language-haskell"><span class="token comment" spellcheck="true">-- Add 1 to every item in the list</span>
<span class="token builtin">map</span> <span class="token punctuation">(</span><span class="token operator">+</span><span class="token number">1</span><span class="token punctuation">)</span> <span class="token punctuation">[</span><span class="token number">1</span><span class="token punctuation">,</span><span class="token number">2</span><span class="token punctuation">,</span><span class="token number">3</span><span class="token punctuation">,</span><span class="token number">4</span><span class="token punctuation">,</span><span class="token number">5</span><span class="token punctuation">]</span> <span class="token comment" spellcheck="true">-- [2,3,4,5,6]</span>

<span class="token comment" spellcheck="true">-- Sum all the values</span>
<span class="token builtin">foldl</span>' <span class="token punctuation">(</span><span class="token operator">+</span><span class="token punctuation">)</span> <span class="token number">0</span> <span class="token punctuation">[</span><span class="token number">1</span><span class="token punctuation">,</span><span class="token number">2</span><span class="token punctuation">,</span><span class="token number">3</span><span class="token punctuation">,</span><span class="token number">4</span><span class="token punctuation">,</span><span class="token number">5</span><span class="token punctuation">]</span> <span class="token comment" spellcheck="true">-- 15</span>

<span class="token comment" spellcheck="true">-- Multiply each number by 2, convert to string and </span>
<span class="token comment" spellcheck="true">-- produce a total string appending the results together</span>
<span class="token builtin">foldl</span>' <span class="token punctuation">(</span><span class="token operator">\</span><span class="token hvariable">acc</span> <span class="token hvariable">n</span> <span class="token operator">-></span> <span class="token hvariable">acc</span> <span class="token operator">++</span> <span class="token builtin">show</span> <span class="token punctuation">(</span><span class="token hvariable">n</span> <span class="token operator">*</span> <span class="token number">2</span><span class="token punctuation">)</span><span class="token punctuation">)</span> <span class="token string">""</span> <span class="token punctuation">[</span><span class="token number">1</span><span class="token punctuation">,</span><span class="token number">2</span><span class="token punctuation">,</span><span class="token number">3</span><span class="token punctuation">,</span><span class="token number">4</span><span class="token punctuation">,</span><span class="token number">5</span><span class="token punctuation">]</span> <span class="token comment" spellcheck="true">-- "246810"</span>

<span class="token comment" spellcheck="true">-- foldl'    (\acc n -> acc ++ show (n * 2))         ""               [1,2,3,4,5]</span>
<span class="token comment" spellcheck="true">-- ^^^^^^    ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^         ^^               ^^^^^^^^^^^</span>
<span class="token comment" spellcheck="true">-- name     binary function that 'does the work'    initial value    list to fold</span></code></pre>
<blockquote>
<p>Q：这些名字是什么意思？<code>map</code>？不是像<code>foreach</code>那样吗？</p>
</blockquote>
<p>是的，但只针对列表。很快你就会发现map不是用来转换列表的，而是根据我们想要映射的东西有不同的语义。如果你想了解更多——可以查看一下<code>Functor</code>，这是一个提供映射接口的高级类型。但是不要太担心<code>Functor</code>——只需要把<code>map</code>看着是一个知道如何迭代数据结构（如列表、树、字典等）的函数就可以了。</p>
<p><code>fold</code>也有更深的含义，与<code>Foldable</code>有关。直觉告诉我们，它会接收一些数据结构并产生单个值，如求和。请注意，<code>map</code>与<code>fold</code>不同，它将函数独立地应用于每个值，而<code>fold</code>可以携带某种依赖于先前值的累加器。</p>
<p>还有更多的函数，但了解这两个函数足以让你在大多数迭代问题上走得更远。</p>
<h2 id="5、你的代码不再是指令列表"><a href="#5、你的代码不再是指令列表" class="headerlink" title="5、你的代码不再是指令列表"></a>5、你的代码不再是指令列表</h2><p>在命令式语言中，你可以这样做：</p>
<pre class=" language-scala"><code class="language-scala"><span class="token keyword">object</span> MyProgram <span class="token keyword">extends</span> App <span class="token punctuation">{</span>
  doThis<span class="token punctuation">(</span><span class="token punctuation">)</span>
  doThat<span class="token punctuation">(</span><span class="token punctuation">)</span>
  doSomethingElse<span class="token punctuation">(</span><span class="token punctuation">)</span>
  printResult<span class="token punctuation">(</span><span class="token punctuation">)</span>
<span class="token punctuation">}</span></code></pre>
<p>这些函数有“副作用”，如它们会<strong>做一些事情</strong>。它们操作的结果是整个程序的状态发生了变化——一些文件被写入磁盘，在控制台输出，更新内部实体映射，等。一旦你调用这样的函数——它就确实被完全执行了。</p>
<blockquote>
<p>好吧，这没什么新鲜的，这就是我通常的编程方式。</p>
</blockquote>
<p>当然，但是在函数式程序中，直到最后一刻之前都不会执行任何操作。你的函数必须接收值并返回值，不允许有副作用。一个函数的输出是另一个函数的输入，而另一个函数又反过来为其它函数创建了输入，以此类推。</p>
<p>这段程序在FP中可能是下面这样的：</p>
<pre class=" language-scala"><code class="language-scala"><span class="token keyword">object</span> MyProgram <span class="token keyword">extends</span> App <span class="token punctuation">{</span>
  unsafeRun<span class="token punctuation">(</span>             <span class="token comment" spellcheck="true">//       &lt;-- This guy takes your pure program </span>
                         <span class="token comment" spellcheck="true">//           and actually runs it</span>
    printResult<span class="token punctuation">(</span>         <span class="token comment" spellcheck="true">// --</span>
      doSomethingElse<span class="token punctuation">(</span>   <span class="token comment" spellcheck="true">//   | </span>
        doThat<span class="token punctuation">(</span>          <span class="token comment" spellcheck="true">//   |</span>
          doThis<span class="token punctuation">(</span><span class="token punctuation">)</span>       <span class="token comment" spellcheck="true">//   | This is your 'pure' part, nothing happened yet</span>
        <span class="token punctuation">)</span>                <span class="token comment" spellcheck="true">//   |</span>
      <span class="token punctuation">)</span>                  <span class="token comment" spellcheck="true">//   |</span>
    <span class="token punctuation">)</span>                    <span class="token comment" spellcheck="true">// --</span>

  <span class="token punctuation">)</span>
<span class="token punctuation">}</span></code></pre>
<p>注意这里的<code>unsafeRun</code>函数（我们假定它是语言提供的）。在<code>unsafeRun</code>之前，我们所做的只是将函数粘在一起，并没有执行任何操作。我们正在构建某种执行计划——“这个函数首先被调用，然后根据它的输出，我们将调用这两个函数中的一个”，等等。</p>
<p>这也不是一个容易掌握的概念，因为我们习惯于在这里抛出一些额外的行为，来做一些事情，比如日志语句或设置一些标志，清除一个队列等等。你不能再这样做了，因为这些附加函数必须遵循类型约束并与其它函数组合。这是一件好事——它迫使我们对程序所做的事更有原则，并确保所有的东西都编码在函数的类型签名中。</p>
<h2 id="6、关于null和异常"><a href="#6、关于null和异常" class="headerlink" title="6、关于null和异常"></a>6、关于null和异常</h2><p>空值在命令式代码库中随处可见。<code>null</code>的问题在于，它是一个较低层次的抽象，被泄露到了更高级别的类型系统中。如果我看到一个函数会返回一个<code>Person</code>，（假定函数是完全的）那么我期望得到一个有名字、地址等任何信息的<code>Person</code>。 <code>null</code>不是一个<code>Person</code>。<code>null</code>通常用于表示不存在或者是某种阻止函数返回正确值的内部故障。如果函数在某些情况下无法返回一个<code>Person</code>，则应该在其类型声明中进行说明。在FP中，我们可以用和类型表示不存在。</p>
<pre class=" language-scala"><code class="language-scala"><span class="token comment" spellcheck="true">// A simple sum type that has two options</span>
<span class="token keyword">sealed</span> <span class="token keyword">trait</span> Option<span class="token punctuation">[</span>A<span class="token punctuation">]</span>

<span class="token comment" spellcheck="true">// A value of some type 'A' (product type with a single field)</span>
<span class="token keyword">case</span> <span class="token keyword">class</span> Some<span class="token punctuation">[</span>A<span class="token punctuation">]</span><span class="token punctuation">(</span>value<span class="token operator">:</span> A<span class="token punctuation">)</span> <span class="token keyword">extends</span> Option<span class="token punctuation">[</span>A<span class="token punctuation">]</span>

<span class="token comment" spellcheck="true">// Type constructor that represents absence of a value</span>
<span class="token keyword">case</span> <span class="token keyword">class</span> None<span class="token punctuation">[</span>A<span class="token punctuation">]</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token keyword">extends</span> Option<span class="token punctuation">[</span>A<span class="token punctuation">]</span>

<span class="token comment" spellcheck="true">// Instead of throwing an exception or crashing the function will</span>
<span class="token comment" spellcheck="true">// return a *value*.</span>
<span class="token keyword">def</span> divide<span class="token punctuation">(</span>dividend<span class="token operator">:</span> <span class="token builtin">Int</span><span class="token punctuation">,</span> divisor<span class="token operator">:</span> <span class="token builtin">Int</span><span class="token punctuation">)</span><span class="token operator">:</span> Option<span class="token punctuation">[</span><span class="token builtin">Int</span><span class="token punctuation">]</span> <span class="token operator">=</span>
  <span class="token keyword">if</span> <span class="token punctuation">(</span>divisor <span class="token operator">==</span> <span class="token number">0</span><span class="token punctuation">)</span>
    None<span class="token punctuation">(</span><span class="token punctuation">)</span>
  <span class="token keyword">else</span>
    Some<span class="token punctuation">(</span>dividend <span class="token operator">/</span> divisor<span class="token punctuation">)</span>

<span class="token comment" spellcheck="true">// And compare it to the usual non total and unsafe function.</span>
<span class="token comment" spellcheck="true">// By looking at the type signature we have no idea if the</span>
<span class="token comment" spellcheck="true">// function is total or not, will it throw or not</span>
<span class="token keyword">def</span> divide<span class="token punctuation">(</span>dividend<span class="token operator">:</span> <span class="token builtin">Int</span><span class="token punctuation">,</span> divisor<span class="token operator">:</span> <span class="token builtin">Int</span><span class="token punctuation">)</span><span class="token operator">:</span> <span class="token builtin">Int</span> <span class="token operator">=</span>
  <span class="token keyword">if</span> <span class="token punctuation">(</span>divisor <span class="token operator">==</span> <span class="token number">0</span><span class="token punctuation">)</span>
    <span class="token keyword">throw</span> <span class="token keyword">new</span> Exception<span class="token punctuation">(</span><span class="token string">"meh"</span><span class="token punctuation">)</span>
  <span class="token keyword">else</span>
    dividend <span class="token operator">/</span> divisor

<span class="token comment" spellcheck="true">// The 'Option' sum type is available in the Scala standard library</span></code></pre>
<pre class=" language-haskell"><code class="language-haskell"><span class="token comment" spellcheck="true">-- Simple sum type with two options</span>
<span class="token keyword">data</span> <span class="token constant">Maybe</span> <span class="token hvariable">a</span> <span class="token operator">=</span> <span class="token constant">Just</span> <span class="token hvariable">a</span> <span class="token operator">|</span> <span class="token constant">Nothing</span>

<span class="token comment" spellcheck="true">-- Safe total function that never throws</span>
<span class="token hvariable">divide</span> <span class="token operator">::</span> <span class="token constant">Int</span> <span class="token operator">-></span> <span class="token constant">Int</span> <span class="token operator">-></span> <span class="token constant">Maybe</span> <span class="token constant">Int</span>
<span class="token hvariable">divide</span> <span class="token hvariable">dividend</span> <span class="token hvariable">divisor</span> <span class="token operator">=</span> <span class="token keyword">if</span> <span class="token hvariable">divisor</span> <span class="token operator">==</span> <span class="token number">0</span> <span class="token keyword">then</span> <span class="token constant">Nothing</span> <span class="token keyword">else</span> <span class="token constant">Just</span> <span class="token punctuation">(</span><span class="token hvariable">dividend</span> <span class="token operator">/</span> <span class="token hvariable">divisor</span><span class="token punctuation">)</span>

<span class="token comment" spellcheck="true">-- Maybe is available in Data.Maybe module</span></code></pre>
<p>如果一个函数返回一个<code>Person</code>的<code>Maybe</code>或<code>Option</code>封装，它明确表示——不保证返回<code>Person</code>。调用者必须检查返回值是<code>Some</code>还是<code>None</code>，这也意味着不再有<code>null</code>解引用问题或<code>null</code>指针异常。</p>
<p>如果你仔细想想，会发现<code>null</code>是一种低层原语，它与运行时系统有关，而与你的程序逻辑无关。当你使用带有垃圾收集功能的高级语言写代码时，你并不关心何时以及如何在内存中分配对象，也不关心你的函数生成的机器码是什么。这就是高级语言的作用——它们创建了一个抽象概念，所以你不必考虑细节。<code>null</code>打破了这种抽象，所以代码会被奇怪的<code>q! = null</code>检查甚至更糟糕的解引用问题所污染。</p>
<p>同样地，异常也是如此。没有必要为了处理异常情况而引入使用特殊语法的特殊机制。在纯程序中，可以用普通值标识不存在、失败或异常。用<code>throw e</code>抛出异常会让函数变得部分化（非完全），这又打破了引用透明性并制造了问题。</p>
<p>如果你使用JVM和java库，你就不得不处理异常问题。在一些特殊情况下使用异常是可以的，比如IO，但要确保它是函数类型的一部分——调用者必须知道函数会抛出、可以抛出什么样的异常，这些约定都可以在编译时检查。</p>
<h2 id="7、Functors-Monads-Applicatives？"><a href="#7、Functors-Monads-Applicatives？" class="headerlink" title="7、Functors, Monads, Applicatives？"></a>7、Functors, Monads, Applicatives？</h2><blockquote>
<p>Q：我经常听到FP人员讨论这些事情，但对我来说没有任何意义。有什么简单的解释吗？</p>
</blockquote>
<p>人们发现了一些通用模式，并根据范畴理论给它们命名。Functors、Monads和Traversables是相当强大和常见的抽象，你到处都能看到它们。这个主题足够单独写一篇文章。但是现在，你还不需要担心它。你最终会了解它们的（甚至可能自己重新发明它们）。熟悉函数组合、高阶函数和多态函数，然后再阅读<a target="_blank" rel="noopener" href="https://medium.com/@olxc/type-classes-explained-a9767f64ed2c">类型类</a>。在那之后，Functors和Monads应该会自然出现。这里的要点是，没有魔法，除了我们在本文中已经讨论过的纯函数和函数组合之外，也没有更多的东西。</p>
<p>希望这篇文章有帮助，如果没有——请给我反馈。正如有人所说，“一旦你理解了Monads，你就失去了向别人解释的能力”，所以我希望这篇文章不会离OOP开发者的日常经历太远。谢谢你的阅读，请享受你的FP之旅。</p>
<hr>
<p>原文： <a target="_blank" rel="noopener" href="https://medium.com/@olxc/switching-from-oop-to-functional-programming-4187698d4d3#8215">Switching from OOP to Functional Programming</a></p>

            </div>
            <hr/>

            

    <div class="reprint" id="reprint-statement">
        
            <div class="reprint__author">
                <span class="reprint-meta" style="font-weight: bold;">
                    <i class="fas fa-user">
                        文章作者:
                    </i>
                </span>
                <span class="reprint-info">
                    <a href="/about" rel="external nofollow noreferrer">Guo Yaxiang</a>
                </span>
            </div>
            <div class="reprint__type">
                <span class="reprint-meta" style="font-weight: bold;">
                    <i class="fas fa-link">
                        文章链接:
                    </i>
                </span>
                <span class="reprint-info">
                    <a href="https://www.codinghonest.space/posts/4a84ab11.html">https://www.codinghonest.space/posts/4a84ab11.html</a>
                </span>
            </div>
            <div class="reprint__notice">
                <span class="reprint-meta" style="font-weight: bold;">
                    <i class="fas fa-copyright">
                        版权声明:
                    </i>
                </span>
                <span class="reprint-info">
                    本博客所有文章除特別声明外，均采用
                    <a href="https://creativecommons.org/licenses/by/4.0/deed.zh" rel="external nofollow noreferrer" target="_blank">CC BY 4.0</a>
                    许可协议。转载请注明来源
                    <a href="/about" target="_blank">Guo Yaxiang</a>
                    !
                </span>
            </div>
        
    </div>

    <script async defer>
      document.addEventListener("copy", function (e) {
        let toastHTML = '<span>复制成功，请遵循本文的转载规则</span><button class="btn-flat toast-action" onclick="navToReprintStatement()" style="font-size: smaller">查看</a>';
        M.toast({html: toastHTML})
      });

      function navToReprintStatement() {
        $("html, body").animate({scrollTop: $("#reprint-statement").offset().top - 80}, 800);
      }
    </script>



            <div class="tag_share" style="display: block;">
                <div class="post-meta__tag-list" style="display: inline-block;">
                    
                        <div class="article-tag">
                            
                                <a href="/tags/%E5%87%BD%E6%95%B0%E5%BC%8F/">
                                    <span class="chip bg-color">函数式</span>
                                </a>
                            
                                <a href="/tags/%E8%AF%91%E6%96%87/">
                                    <span class="chip bg-color">译文</span>
                                </a>
                            
                                <a href="/tags/Scala/">
                                    <span class="chip bg-color">Scala</span>
                                </a>
                            
                                <a href="/tags/Haskell/">
                                    <span class="chip bg-color">Haskell</span>
                                </a>
                            
                        </div>
                    
                </div>
                <div class="post_share" style="zoom: 80%; width: fit-content; display: inline-block; float: right; margin: -0.15rem 0;">
                    <link rel="stylesheet" type="text/css" href="/libs/share/css/share.min.css">
<div id="article-share">

    
    <div class="social-share" data-sites="twitter,facebook,google,qq,qzone,wechat,weibo,douban,linkedin" data-wechat-qrcode-helper="<p>微信扫一扫即可分享！</p>"></div>
    <script src="/libs/share/js/social-share.min.js"></script>
    

    

</div>

                </div>
            </div>
            
                <style>
    #reward {
        margin: 40px 0;
        text-align: center;
    }

    #reward .reward-link {
        font-size: 1.4rem;
        line-height: 38px;
    }

    #reward .btn-floating:hover {
        box-shadow: 0 6px 12px rgba(0, 0, 0, 0.2), 0 5px 15px rgba(0, 0, 0, 0.2);
    }

    #rewardModal {
        width: 320px;
        height: 350px;
    }

    #rewardModal .reward-title {
        margin: 15px auto;
        padding-bottom: 5px;
    }

    #rewardModal .modal-content {
        padding: 10px;
    }

    #rewardModal .close {
        position: absolute;
        right: 15px;
        top: 15px;
        color: rgba(0, 0, 0, 0.5);
        font-size: 1.3rem;
        line-height: 20px;
        cursor: pointer;
    }

    #rewardModal .close:hover {
        color: #ef5350;
        transform: scale(1.3);
        -moz-transform:scale(1.3);
        -webkit-transform:scale(1.3);
        -o-transform:scale(1.3);
    }

    #rewardModal .reward-tabs {
        margin: 0 auto;
        width: 210px;
    }

    .reward-tabs .tabs {
        height: 38px;
        margin: 10px auto;
        padding-left: 0;
    }

    .reward-content ul {
        padding-left: 0 !important;
    }

    .reward-tabs .tabs .tab {
        height: 38px;
        line-height: 38px;
    }

    .reward-tabs .tab a {
        color: #fff;
        background-color: #ccc;
    }

    .reward-tabs .tab a:hover {
        background-color: #ccc;
        color: #fff;
    }

    .reward-tabs .wechat-tab .active {
        color: #fff !important;
        background-color: #22AB38 !important;
    }

    .reward-tabs .alipay-tab .active {
        color: #fff !important;
        background-color: #019FE8 !important;
    }

    .reward-tabs .reward-img {
        width: 210px;
        height: 210px;
    }
</style>

<div id="reward">
    <a href="#rewardModal" class="reward-link modal-trigger btn-floating btn-medium waves-effect waves-light red">赏</a>

    <!-- Modal Structure -->
    <div id="rewardModal" class="modal">
        <div class="modal-content">
            <a class="close modal-close"><i class="fas fa-times"></i></a>
            <h4 class="reward-title">你的赏识是我前进的动力</h4>
            <div class="reward-content">
                <div class="reward-tabs">
                    <ul class="tabs row">
                        <li class="tab col s6 alipay-tab waves-effect waves-light"><a href="#alipay">支付宝</a></li>
                        <li class="tab col s6 wechat-tab waves-effect waves-light"><a href="#wechat">微 信</a></li>
                    </ul>
                    <div id="alipay">
                        <img src="/medias/reward/alipay.png" class="reward-img" alt="支付宝打赏二维码">
                    </div>
                    <div id="wechat">
                        <img src="/medias/reward/wechat.png" class="reward-img" alt="微信打赏二维码">
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

<script>
    $(function () {
        $('.tabs').tabs();
    });
</script>

            
        </div>
    </div>

    

    

    

    

    

    
        <style>
    .mvaline-card {
        margin: 1.5rem auto;
    }

    .mvaline-card .card-content {
        padding: 20px 20px 5px 20px;
    }
</style>

<div class="card mvaline-card" data-aos="fade-up">
    <div class="comment_headling" style="font-size: 20px; font-weight: 700; position: relative; padding-left: 20px; top: 15px; padding-bottom: 5px;">
        <i class="fas fa-comments fa-fw" aria-hidden="true"></i>
        <span>评论</span>
    </div>
    <div id="mvcomments" class="card-content" style="display: grid">
    </div>
</div>

<script src="/libs/minivaline/MiniValine.js"></script>
<script>
    new MiniValine({
        el: '#mvcomments',
        appId: 'oqAo7rCWejwTqHjGC2APTVDX-MdYXbMMI',
        appKey: 'pfyY919tO7iJaDm7lFmvh5Wp',
        mode: 'DesertsP',
        placeholder: 'Write a Comment',
        pathname: window.location.pathname,
        lang: '',
        adminEmailMd5: '8BBC105436DAAF8C803841C8FD13CD0C',
        tagMeta: ["管理员", "小伙伴", "访客"],
        master: ["8BBC105436DAAF8C803841C8FD13CD0C"],
        friends: ["FA21C7921CD42FE9523E957870873F64", "586BAB41BB5692877F7714DFE4947DEC"],
        math: true,
        md: true,
        enableQQ: false,
        NoRecordIP: false,
        visitor: true,
        maxNest: 6,
        pageSize: 6,
        serverURLs: '',
        emoticonUrl: ["https://cdn.jsdelivr.net/npm/alus@latest", "https://cdn.jsdelivr.net/gh/MiniValine/qq@latest", "https://cdn.jsdelivr.net/gh/MiniValine/Bilibilis@latest", "https://cdn.jsdelivr.net/gh/MiniValine/tieba@latest", "https://cdn.jsdelivr.net/gh/MiniValine/twemoji@latest", "https://cdn.jsdelivr.net/gh/MiniValine/weibo@latest"],
    });
</script>

    

    

    

<article id="prenext-posts" class="prev-next articles">
    <div class="row article-row">
        
        <div class="article col s12 m6" data-aos="fade-up" data-aos="fade-up">
            <div class="article-badge left-badge text-color">
                <i class="far fa-dot-circle"></i>&nbsp;本篇
            </div>
            <div class="card">
                <a href="/posts/4a84ab11.html">
                    <div class="card-image">
                        
                        
                        <img src="/medias/featureimages/14.jpg" class="responsive-img" alt="【译】从OOP到函数式">
                        
                        <span class="card-title">【译】从OOP到函数式</span>
                    </div>
                </a>
                <div class="card-content article-content">
                    <div class="summary block-with-text">
                        
                            在本文中，将尝试分解一下概念，并回答在从OOP切换FP时会带来困扰的常见问题。
                        
                    </div>
                    <div class="publish-info">
                            <span class="publish-date">
                                <i class="far fa-clock fa-fw icon-date"></i>2021-08-24
                            </span>
                        <span class="publish-author">
                            
                            <i class="fas fa-bookmark fa-fw icon-category"></i>
                            
                            <a href="/categories/%E5%87%BD%E6%95%B0%E5%BC%8F/" class="post-category">
                                    函数式
                                </a>
                            
                            
                        </span>
                    </div>
                </div>

                
                <div class="card-action article-tags">
                    
                    <a href="/tags/%E5%87%BD%E6%95%B0%E5%BC%8F/">
                        <span class="chip bg-color">函数式</span>
                    </a>
                    
                    <a href="/tags/%E8%AF%91%E6%96%87/">
                        <span class="chip bg-color">译文</span>
                    </a>
                    
                    <a href="/tags/Scala/">
                        <span class="chip bg-color">Scala</span>
                    </a>
                    
                    <a href="/tags/Haskell/">
                        <span class="chip bg-color">Haskell</span>
                    </a>
                    
                </div>
                
            </div>
        </div>
        
        
        <div class="article col s12 m6" data-aos="fade-up">
            <div class="article-badge right-badge text-color">
                下一篇&nbsp;<i class="fas fa-chevron-right"></i>
            </div>
            <div class="card">
                <a href="/posts/b23f3fc.html">
                    <div class="card-image">
                        
                        
                        <img src="/medias/featureimages/2.jpg" class="responsive-img" alt="MapStruct使用指南">
                        
                        <span class="card-title">MapStruct使用指南</span>
                    </div>
                </a>
                <div class="card-content article-content">
                    <div class="summary block-with-text">
                        
                            在本文中，我们探讨了MapStruct——一个用于创建映射器类的库。从基本映射到自定义方法和自定义映射器，此外， 我们还介绍了MapStruct提供的一些高级操作选项，包括依赖注入，数据类型映射、枚举映射和表达式使用。
                        
                    </div>
                    <div class="publish-info">
                            <span class="publish-date">
                                <i class="far fa-clock fa-fw icon-date"></i>2021-04-30
                            </span>
                        <span class="publish-author">
                            
                            <i class="fas fa-bookmark fa-fw icon-category"></i>
                            
                            <a href="/categories/Java/" class="post-category">
                                    Java
                                </a>
                            
                            <a href="/categories/Java/%E6%95%88%E7%8E%87%E5%B7%A5%E5%85%B7/" class="post-category">
                                    效率工具
                                </a>
                            
                            
                        </span>
                    </div>
                </div>
                
                <div class="card-action article-tags">
                    
                    <a href="/tags/Java/">
                        <span class="chip bg-color">Java</span>
                    </a>
                    
                    <a href="/tags/%E6%95%88%E7%8E%87%E5%B7%A5%E5%85%B7/">
                        <span class="chip bg-color">效率工具</span>
                    </a>
                    
                </div>
                
            </div>
        </div>
        
    </div>
</article>

</div>


<script>
    $('#articleContent').on('copy', function (e) {
        // IE8 or earlier browser is 'undefined'
        if (typeof window.getSelection === 'undefined') return;

        var selection = window.getSelection();
        // if the selection is short let's not annoy our users.
        if (('' + selection).length < Number.parseInt('120')) {
            return;
        }

        // create a div outside of the visible area and fill it with the selected text.
        var bodyElement = document.getElementsByTagName('body')[0];
        var newdiv = document.createElement('div');
        newdiv.style.position = 'absolute';
        newdiv.style.left = '-99999px';
        bodyElement.appendChild(newdiv);
        newdiv.appendChild(selection.getRangeAt(0).cloneContents());

        // we need a <pre> tag workaround.
        // otherwise the text inside "pre" loses all the line breaks!
        if (selection.getRangeAt(0).commonAncestorContainer.nodeName === 'PRE') {
            newdiv.innerHTML = "<pre>" + newdiv.innerHTML + "</pre>";
        }

        var url = document.location.href;
        newdiv.innerHTML += '<br />'
            + '来源: 码道诚公<br />'
            + '文章作者: Guo Yaxiang<br />'
            + '文章链接: <a href="' + url + '">' + url + '</a><br />'
            + '本文章著作权归作者所有，任何形式的转载都请注明出处。';

        selection.selectAllChildren(newdiv);
        window.setTimeout(function () {bodyElement.removeChild(newdiv);}, 200);
    });
</script>


<!-- 代码块功能依赖 -->
<script type="text/javascript" src="/libs/codeBlock/codeBlockFuction.js"></script>

<!-- 代码语言 -->

<script type="text/javascript" src="/libs/codeBlock/codeLang.js"></script>


<!-- 代码块复制 -->

<script type="text/javascript" src="/libs/codeBlock/codeCopy.js"></script>


<!-- 代码块收缩 -->

<script type="text/javascript" src="/libs/codeBlock/codeShrink.js"></script>


<!-- 代码块折行 -->

<style type="text/css">
code[class*="language-"], pre[class*="language-"] { white-space: pre !important; }
</style>


    </div>
    <div id="toc-aside" class="expanded col l3 hide-on-med-and-down">
        <div class="toc-widget card" style="background-color: white;">
            <div class="toc-title"><i class="far fa-list-alt"></i>&nbsp;&nbsp;目录</div>
            <div id="toc-content"></div>
        </div>
    </div>
</div>

<!-- TOC 悬浮按钮. -->

<div id="floating-toc-btn" class="hide-on-med-and-down">
    <a class="btn-floating btn-large bg-color">
        <i class="fas fa-list-ul"></i>
    </a>
</div>


<script src="/libs/tocbot/tocbot.min.js"></script>
<script>
    $(function () {
        tocbot.init({
            tocSelector: '#toc-content',
            contentSelector: '#articleContent',
            headingsOffset: -($(window).height() * 0.4 - 45),
            collapseDepth: Number('0'),
            headingSelector: 'h2, h3, h4'
        });

        // modify the toc link href to support Chinese.
        let i = 0;
        let tocHeading = 'toc-heading-';
        $('#toc-content a').each(function () {
            $(this).attr('href', '#' + tocHeading + (++i));
        });

        // modify the heading title id to support Chinese.
        i = 0;
        $('#articleContent').children('h2, h3, h4').each(function () {
            $(this).attr('id', tocHeading + (++i));
        });

        // Set scroll toc fixed.
        let tocHeight = parseInt($(window).height() * 0.4 - 64);
        let $tocWidget = $('.toc-widget');
        $(window).scroll(function () {
            let scroll = $(window).scrollTop();
            /* add post toc fixed. */
            if (scroll > tocHeight) {
                $tocWidget.addClass('toc-fixed');
            } else {
                $tocWidget.removeClass('toc-fixed');
            }
        });

        
        /* 修复文章卡片 div 的宽度. */
        let fixPostCardWidth = function (srcId, targetId) {
            let srcDiv = $('#' + srcId);
            if (srcDiv.length === 0) {
                return;
            }

            let w = srcDiv.width();
            if (w >= 450) {
                w = w + 21;
            } else if (w >= 350 && w < 450) {
                w = w + 18;
            } else if (w >= 300 && w < 350) {
                w = w + 16;
            } else {
                w = w + 14;
            }
            $('#' + targetId).width(w);
        };

        // 切换TOC目录展开收缩的相关操作.
        const expandedClass = 'expanded';
        let $tocAside = $('#toc-aside');
        let $mainContent = $('#main-content');
        $('#floating-toc-btn .btn-floating').click(function () {
            if ($tocAside.hasClass(expandedClass)) {
                $tocAside.removeClass(expandedClass).hide();
                $mainContent.removeClass('l9');
            } else {
                $tocAside.addClass(expandedClass).show();
                $mainContent.addClass('l9');
            }
            fixPostCardWidth('artDetail', 'prenext-posts');
        });
        
    });
</script>

    

</main>




    <footer class="page-footer bg-color">
    
        <link rel="stylesheet" href="/libs/aplayer/APlayer.min.css">
<style>
    .aplayer .aplayer-lrc p {
        
        display: none;
        
        font-size: 12px;
        font-weight: 700;
        line-height: 16px !important;
    }

    .aplayer .aplayer-lrc p.aplayer-lrc-current {
        
        display: none;
        
        font-size: 15px;
        color: #42b983;
    }

    
    .aplayer.aplayer-fixed.aplayer-narrow .aplayer-body {
        left: -66px !important;
    }

    .aplayer.aplayer-fixed.aplayer-narrow .aplayer-body:hover {
        left: 0px !important;
    }

    
</style>
<div class="">
    
    <div class="row">
        <meting-js class="col l8 offset-l2 m10 offset-m1 s12"
                   server="netease"
                   type="playlist"
                   id="503838841"
                   fixed='true'
                   autoplay='false'
                   theme='#42b983'
                   loop='all'
                   order='random'
                   preload='auto'
                   volume='0.7'
                   list-folded='true'
        >
        </meting-js>
    </div>
</div>

<script src="/libs/aplayer/APlayer.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/meting@2/dist/Meting.min.js"></script>

    
    <div class="container row center-align" style="margin-bottom: 0px !important;">
        <div class="col s12 m8 l8 copy-right">
            Copyright&nbsp;&copy;
            
                <span id="year">2020-2021</span>
            
            <span id="year">2020</span>
            <a href="/about" target="_blank">Guo Yaxiang</a>
            |&nbsp;Powered by&nbsp;<a href="https://hexo.io/" target="_blank">Hexo</a>
            |&nbsp;Theme&nbsp;<a href="https://github.com/blinkfox/hexo-theme-matery" target="_blank">Matery</a>
            <br>
            
            
            
            
            
            <br>
            
            <br>
            
        </div>
        <div class="col s12 m4 l4 social-link ">
    <a href="https://github.com/GuoYaxiang" class="tooltipped" target="_blank" data-tooltip="访问我的GitHub" data-position="top" data-delay="50">
        <i class="fab fa-github"></i>
    </a>



    <a href="mailto:YXGyxg112358@163.com" class="tooltipped" target="_blank" data-tooltip="邮件联系我" data-position="top" data-delay="50">
        <i class="fas fa-envelope-open"></i>
    </a>







    <a href="tencent://AddContact/?fromId=50&fromSubId=1&subcmd=all&uin=1431800679" class="tooltipped" target="_blank" data-tooltip="QQ联系我: 1431800679" data-position="top" data-delay="50">
        <i class="fab fa-qq"></i>
    </a>





    <a href="https://www.zhihu.com/people/guo-ya-xiang" class="tooltipped" target="_blank" data-tooltip="关注我的知乎: https://www.zhihu.com/people/guo-ya-xiang" data-position="top" data-delay="50">
        <i class="fab fa-zhihu1">知</i>
    </a>



    <a href="/atom.xml" class="tooltipped" target="_blank" data-tooltip="RSS 订阅" data-position="top" data-delay="50">
        <i class="fas fa-rss"></i>
    </a>

</div>
    </div>
</footer>

<div class="progress-bar"></div>


    <!-- 搜索遮罩框 -->
<div id="searchModal" class="modal">
    <div class="modal-content">
        <div class="search-header">
            <span class="title"><i class="fas fa-search"></i>&nbsp;&nbsp;搜索</span>
            <input type="search" id="searchInput" name="s" placeholder="请输入搜索的关键字"
                   class="search-input">
        </div>
        <div id="searchResult"></div>
    </div>
</div>

<script src="/js/search.js"></script>
<script type="text/javascript">
$(function () {
    searchFunc('/search.xml', 'searchInput', 'searchResult');
});
</script>

    <!-- 回到顶部按钮 -->
<div id="backTop" class="top-scroll">
    <a class="btn-floating btn-large waves-effect waves-light" href="#!">
        <i class="fas fa-arrow-up"></i>
    </a>
</div>


    <script src="/libs/materialize/materialize.min.js"></script>
    <script src="/libs/masonry/masonry.pkgd.min.js"></script>
    <script src="/libs/aos/aos.js"></script>
    <script src="/libs/scrollprogress/scrollProgress.min.js"></script>
    <script src="/libs/lightGallery/js/lightgallery-all.min.js"></script>
    <script src="/js/matery.js"></script>

    <!-- Baidu Analytics -->

    <!-- Baidu Push -->

<script>
    (function () {
        var bp = document.createElement('script');
        var curProtocol = window.location.protocol.split(':')[0];
        if (curProtocol === 'https') {
            bp.src = 'https://zz.bdstatic.com/linksubmit/push.js';
        } else {
            bp.src = 'http://push.zhanzhang.baidu.com/push.js';
        }
        var s = document.getElementsByTagName("script")[0];
        s.parentNode.insertBefore(bp, s);
    })();
</script>

    
    <script src="/libs/others/clicklove.js" async="async"></script>
    
    

    
        <script src="//code.tidio.co/zgiqinzrat1rzwxseqhr2pnzsp2a4rjo.js"></script>
        <script>
            $(document).ready(function () {
                setInterval(change_Tidio, 50);
                function change_Tidio() {
                    var tidio=$("#tidio-chat iframe");
                    if(tidio.css("display")=="block"&& $(window).width()>977 ){
                        document.getElementById("tidio-chat-iframe").style.bottom= ($("div#backTop.top-scroll").css("display")=="none" &&$(window).width()>977)>0? "-40px" : ($("div.toc-title").length&&$(window).width()>977)>0?"85px":"20px";
                        document.getElementById("tidio-chat-iframe").style.right="-15px";
                        document.getElementById("tidio-chat-iframe").style.height=parseInt(tidio.css("height"))>=520?"520px":tidio.css("height");
                        document.getElementById("tidio-chat-iframe").style.zIndex="997";
                    }
                    else if(tidio.css("display")=="block"&&$(window).width()>601 &&$(window).width()<992 ){
                        document.getElementById("tidio-chat-iframe").style.bottom= ($("div#backTop.top-scroll").css("display")=="none" && 601< $(window).width()<992)>0? "-40px":"20px" ;
                        document.getElementById("tidio-chat-iframe").style.right="-15px";
                        document.getElementById("tidio-chat-iframe").style.zIndex="997";
                    }
                    else if(tidio.css("display")=="block"&&$(window).width()<601 && parseInt(tidio.css("height"))<230){
                        document.getElementById("tidio-chat-iframe").style.bottom= ($("div#backTop.top-scroll").css("display")=="none" && $(window).width()<601)>0? "-10px":"45px" ;
                        document.getElementById("tidio-chat-iframe").style.zIndex="997";
                    }
                    if( tidio.css("display")=="block"&&$(window).width()<601 && parseInt(tidio.css("height"))>=230){
                        document.getElementById("tidio-chat-iframe").style.zIndex="998";
                    }
                }
            });
        </script>
    

    

    

    

    

    
    <script src="/libs/instantpage/instantpage.js" type="module"></script>
    

</body>

</html>
